import React from 'react';
import Box from '@material-ui/core/Box';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import Plot from 'react-plotly.js';
import history from './history'
import * as d3 from 'd3'


class App extends React.Component {
  constructor(props) {
    super(props);
    this.handleCSV = this.handleCSV.bind(this);
    this.handleRoot = this.handleRoot.bind(this);
    this.handleDir = this.handleDir.bind(this);
    this.path = "";
    this.state = {
      path: "",
      value: "",
      root_dir: "",
      options: [],
    };

    let path = this.props.location.pathname;
    if (path) {
      // path start from /
      let prefix = "/plot";
      if (path.startsWith(prefix)) {
        path = path.slice(prefix.length);
      }
      let dir = path.substring(0, path.lastIndexOf('/'));
      this.path = dir.slice(1);
      this.getOptions(dir);
      if (path.slice(-4) == '.csv') {
        this.getCSV(path);
      }
      this.state.value = path.slice(1);
    } else {
      this.getOptions("");
    }

    fetch("/root_dir").then(response => response.text()).then(this.handleRoot);
  }

  handleRoot(body) {
    this.setState({root_dir: body});
  }

  handleCSV(rows) {
    function unpack(rows, key) {
      return rows.map(function(row) {
        return row[key];
      });
    }

    var trace = {
      x: unpack(rows, 'time'),
      close: unpack(rows, 'open'),
      high: unpack(rows, 'high'),
      low: unpack(rows, 'low'),
      open: unpack(rows, 'open'),
    
      // cutomise colors
      increasing: {line: {color: 'black'}},
      decreasing: {line: {color: 'red'}},
    
      type: 'candlestick',
      xaxis: 'x',
      yaxis: 'y'
    };
    
    var data = [trace];
    
    var layout = {
      displayModeBar: false,
      yaxis: {
        autorange: true,
      }
    };

    this.setState({
      data: {
        data: data,
        layout: layout
      }
    });
  }

  handleDir(text) {
    let options = text.split("\n");
    let prefix = "";
    if (this.path) {
      prefix = this.path + "/";
    }

    let array = options.map(el => prefix + el);
    this.setState({options: [...array]});
  }

  handleInput(newInputValue) {
    let dir = newInputValue.substring(0, newInputValue.lastIndexOf('/'));
    let last_dir = this.state.path.substring(0, this.state.path.lastIndexOf('/'));
    if (dir != last_dir) {
      this.path = dir;
      this.getOptions("/" + dir);
    }
    this.setState({path: newInputValue});
  }

  getOptions(url) {
    fetch("/data" + url)
    .then(response => response.text())
    .then(this.handleDir)
    .catch(error => console.error(error));
  }
  getCSV(url) {
    d3.csv('/data' + url).then(this.handleCSV);
  }

  render() {
    return (
      <Box>
        <Autocomplete
          value={this.state.value}
          onChange={(event, newValue) => {
            if (!newValue) {
              return;
            }
            if (newValue && newValue.slice(-4) == '.csv') {
              let path = "/" + newValue
              this.getCSV(path);
              this.state.value=newValue;
              history.push("/plot" + path);
            } else {
              let value = newValue  + "/"
              this.state.value=value;
              this.handleInput(value)
            }
          }}
          onInputChange={(event, newInputValue) => {
            if (!newInputValue) {
              newInputValue = "";
            }
            this.handleInput(newInputValue)
          }}
          id="controllable-states-select"
          disableCloseOnSelect
          options={this.state.options}
          style={{ width: 640, padding: 20 }}
          renderInput={(params) => <TextField {...params} label={this.state.root_dir} variant="outlined" />}
        />
        { this.state.data != null && (
          <Plot
            data={this.state.data.data}
            layout={ this.state.data.layout }
          />)
        }
      </Box>
    );
  }
}

export default App;
